# coding=utf-8

from rest_framework import serializers
from utils.exceptions import CustomError
from apps.account.models import User

class UserSerializer(serializers.ModelSerializer):
    type = serializers.IntegerField(read_only=True)
    password = serializers.CharField(write_only=True, allow_blank=True)

    class Meta:
        model = User
        fields = '__all__'

    def create(self, validated_data):
        validated_data['type'] = User.ADMINSTRATOR
        if validated_data['password'].strip() == '':
            raise CustomError(u'密码不能为空！')
        instance = super(UserSerializer, self).create(validated_data)
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    def update(self, instance, validated_data):
        instance.update_item(validated_data)
        # if not 'password' in validated_data or not validated_data['password']:
        #     validated_data['password'] = instance.password
        #     instance = super(UserSerializer, self).update(instance, validated_data)
        # else:
        #     instance = super(UserSerializer, self).update(instance, validated_data)
        #     instance.set_password(validated_data['password'])
        # instance.save()
        return instance